import React, { useState, useEffect } from "react"
import Dialog from '../components/Dialog'
import { useRequest } from "../useRequest"
import { cosApi } from '../apis/cosApi'
import { hostApi } from '../apis/hostAip'
import { House, HousePics, Meet } from "../types/base"
import './SendHouse.scss'
import './out.scss'
let COS = require('cos-js-sdk-v5');

const bucket = 'host-sys-1300288893'
const region = 'ap-nanjing'
interface upHouseDialogProps {
    show: boolean
    hide: () => void
    cos: any
    user: any
}
const UpHouseDialog: React.FC<upHouseDialogProps> = (props) => {
    const { show, hide, cos } = props

    const { response: addRe, send: addHouse, setResponse: setAddRe } = useRequest(hostApi.addHouse)
    const [description, setDescription] = useState<string>(null)
    const [location, setLocation] = useState<string>(null)
    const [HouseType, setHouseType] = useState<string>(null);
    const [showAddSuccess, setshowAddSuccess] = useState<boolean>(false);
    const [missingHouse, setmissingHouse] = useState<boolean>(false);

    const [innum, setinnum] = useState([0]);

    useEffect(() => {
        if (!show) return
    }, [show])

    let uploads = (houseID: number) => {
        let len = document.getElementsByName('fff').length
        for (let i = 0; i < len; i++) {
            let file = document.getElementsByName('fff')[i].files[0]
            if (!file) {
                continue
            }
            let img = new Image()
            img.src = URL.createObjectURL(file)

            img.onload = () => {
                uploadPic('house/' + props.user.username + '/house_' + houseID + '/pic_' + i, file, img.width, img.height)
            }
        }
    }
    let uploadPic = (key: string, file: File, w, h) => {
        cos.putObject({
            Bucket: bucket,
            Region: region,
            Key: key,              /* 必须 */
            StorageClass: 'STANDARD',
            Body: file, // 上传文件对象
            onProgress: function (progressData) {
                console.log(JSON.stringify(progressData));
            }
        }, async function (err, data) {
            if (data && data.Location) {
                await hostApi.addPic({ url: 'https://' + data.Location, houseID: addRe, width: w, height: h })
            }
            else
                console.log(err)
        });
    }

    const submitAdd = () => {
        if (!location || !description || !HouseType) {
            setmissingHouse(true)
            return
        }
        addHouse({ description, location, type: HouseType })
    }
    useEffect(() => {
        if (!addRe) return
        uploads(addRe)
        setshowAddSuccess(true)
        setAddRe(null)
    }, [addRe])

    const closeModel = () => {
        setDescription(null)
        setLocation(null)
        setHouseType(null)
        setshowAddSuccess(false)
        setmissingHouse(false)

        setinnum([0])
        hide()
    }
    let addIn = () => {
        let len = innum.length
        let a = Array(len + 1)
        for (let i = 0; i < len + 1; i++)a[i] = 0
        setinnum(a)
    }
    let ddIn = () => {
        let len = innum.length
        let a = Array(len - 1)
        for (let i = 0; i < len - 1; i++)a[i] = 0
        setinnum(a)
    }
    const [picClick, setpicClick] = useState(1);
    let click = (i) => {
        document.getElementsByName('fff')[i].click()
    }

    return (
        <Dialog
            title='新增房源'
            show={show}
            onClose={closeModel}
            className=''
        >
            {!showAddSuccess ?
                (
                    <div className='upDia'>
                        <span className={`input input--juro ${location ? 'input--filled' : ''}`}>
                            <input className="input__field input__field--juro" type="text" id="input-28"
                                value={location} onInput={(ev) => { setLocation(ev.target.value) }} />
                            <label className="input__label input__label--juro" htmlFor="input-28">
                                <span className="input__label-content input__label-content--juro">地址</span>
                            </label>
                        </span>
                        <br />
                        <span className='upDia-radio'>
                            <label> 单间 <input name="xx" type='radio' value='a' onChange={() => { setHouseType('单间') }} /></label>
                            <label> 套间 <input name="xx" type='radio' value='b' onChange={() => { setHouseType('套间') }} /></label>
                        </span>
                        <br />
                        <span className={`input input--juro ${description ? 'input--filled' : ''}`}>
                            <input className="input__field input__field--juro" type="text" id="input-29"
                                value={description} onInput={(ev) => { setDescription(ev.target.value) }} />
                            <label className="input__label input__label--juro" htmlFor="input-29">
                                <span className="input__label-content input__label-content--juro">描述</span>
                            </label>
                        </span>
                        <br />
                        {innum.map((item, index) => (
                            <div className={`addpicdiv`}>
                                <input className='hide' onChange={() => { setpicClick(picClick + 1) }} type="file" name="fff" accept="image/*"></input>
                                {picClick ? (
                                    <span className='addpicname' onClick={() => { click(index) }}>{
                                        document.getElementsByName('fff')[index] ? (
                                            document.getElementsByName('fff')[index].files[0] ?
                                                document.getElementsByName('fff')[index].files[0].name :
                                                '添加图片') : '添加图片'
                                    }
                                    </span>) : <span></span>}
                                {index + 1 === innum.length ?
                                    <span className='upDia-add' onClick={addIn}>+</span> :
                                    <span className='upDia-add' onClick={ddIn}>-</span>
                                }
                            </div>
                        ))}
                        <br />
                        <div className='upDia-sub' onClick={submitAdd}>提交</div>
                        {missingHouse && (<span>请填写完整信息</span>)}
                    </div>
                ) :
                (
                    <div className='adsuccess'>
                        <h3>添加成功</h3>

                        <div className='adsuccess-con' onClick={closeModel}>确定</div>
                    </div>
                )}
        </Dialog>
    )
}

interface HouseDetailDialogProps {
    show: boolean
    hide: () => void
    user: any
    house: House
}

const HouseDetailDialog: React.FC<HouseDetailDialogProps> = (props) => {
    const { show, hide, user, house } = props
    const [pics, setpics] = useState(null);
    useEffect(() => {
        if (!house) return
        setpics(house.pics)
    }, [house])


    return (
        <Dialog
            title='房间详情'
            show={show}
            onClose={hide}
            className=''
        >
            <div className="details" v-show="details">
                <div>
                    <h1>房间详情</h1>
                </div>
                <div className="detailPic">
                    <div className="pic-title">房间图片</div>
                    <div className="pic-content">
                        {pics && pics.length > 0 && pics.map((item: HousePics, i) => (
                            <div className="detailPicture">
                                <img src={item.url} />
                            </div>
                        ))}

                    </div>
                </div>
                {house && (
                    <div>
                        <div className="detailType">房源类型:{house.type}</div>
                        <div className="detailAddress">房源地址:{house.location}</div>
                        <div className="detailDescription">房间描述:{house.description}</div>
                        <div className="hostPhone">房主电话:{house.hostMan.phone}</div>
                    </div>
                )}
            </div>
        </Dialog>
    )
}

interface MeetDialogProps {
    show: boolean
    hide: () => void
    user: any
    meets: any
}

const MeetDialog: React.FC<MeetDialogProps> = (props) => {
    const { show, hide, meets } = props

    const closeModel = () => {
        hide()
    }
    let conv = (a: string) => {
        let res = new Date()
        res.setTime(Date.parse(a))
        let M = res.getMonth() + 1
        let d = res.getDate()
        let h = res.getHours()
        let m = res.getMinutes()
        let m_tmp
        if (m === 0) m_tmp = '00'
        else if (m < 10) m_tmp = '0' + m
        else m_tmp = m + ''
        return M + '月' + d + '日 ' + h + ':' + m_tmp
    }
    return (
        <Dialog
            title='消息'
            show={show}
            onClose={closeModel}
            className=''
        >
            <div>
                <div>
                    {meets && meets.length > 0 &&
                        meets.map((meet: Meet, i: number) => (
                            <div className='d-message'>
                                <div>
                                    {meet.house &&
                                        <div>
                                            <div>房源地址: {meet.house.location}</div>
                                            <div>房源类型: {meet.house.type}</div>
                                        </div>
                                    }
                                </div>
                                <div>会面时间: {conv(meet.time)}</div>
                            </div>
                        ))}
                    <div className="blank"></div>
                </div>
            </div>
        </Dialog>
    )
}

interface sendHouseProps {
    // show: () => void
    // hide: () => void
}
const SendHouse: React.FC<sendHouseProps> = (props) => {

    let logout = async () => {
        await window.fetch('/logout', { method: 'post' })
        window.location.replace('/')
    }

    const [showHouseDialog, setshowHouseDialog] = useState(false);
    const [showMeetDialog, setshowMeetDialog] = useState(false);
    const [showHouseDetailDialog, setshowHouseDetailDialog] = useState(false);

    const { response: meets, send: getMeet } = useRequest(hostApi.getMeet);
    const { response: user, send: getRole } = useRequest(hostApi.getRole);
    const { response: getHouseRe, send: getHouse, setResponse: setgetHouseRe, reset } = useRequest(hostApi.getHouse)
    const [houses, sethouses] = useState<any | null>(null)
    const [show, setshow] = useState(false);
    const [d_house, setd_house] = useState(null);

    if (!show) setshow(true)
    useEffect(() => {
        if (!show) return
        console.log('19-37')
        getHouse()
        getRole()
        getMeet()
        // getCred({})
    }, [show])
    let cos = new COS({
        getAuthorization: function (options, callback) {
            window.fetch('getCred', {
                method: 'post',
            })
                .then(r => {
                    return r.json()
                })
                .then(j => {
                    let data = j.data
                    let credentials = data && data.credentials;
                    if (!data || !credentials) return console.error('credentials invalid');
                    callback({
                        TmpSecretId: credentials.tmpSecretId,
                        TmpSecretKey: credentials.tmpSecretKey,
                        XCosSecurityToken: credentials.sessionToken,
                        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                        StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                        ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
                    });
                })
        }
    })
    useEffect(() => {
        if (!getHouseRe) return
        sethouses(getHouseRe)
        setgetHouseRe(null)
    }, [getHouseRe, getHouse])

    let houmap = []
    useEffect(() => {
        if (!houses) return
        for (let i = 0; i < houses.length; i++) {
            let house = houses[i]
            if (house.pics && house.pics.length > 0) houmap.push(i)
        }
        calcu()
    }, [houses]);

    let calcu = () => {
        let pics = document.getElementsByClassName('pic-img')
        for (let i = 0; i < pics.length; i++) {
            let w = houses[houmap[i]].pics[0].width
            let h = houses[houmap[i]].pics[0].height
            let tmp = 200 * w / h
            pics[i].style.marginLeft = ((200 - tmp) / 2) + 'px'
        }
    }
    let showHouseDetail = (house) => {
        setd_house(house)
        setshowHouseDetailDialog(true)
    }

    return (
        <div className="acbc">
            <div className="nav">
                <div className="back-home" onClick={() => { window.location.replace('/user/home') }}>返回</div>
                <p>Hello,{user ? user.name : null}</p>
                <div className="message" onClick={() => { setshowMeetDialog(true) }}>消息</div>
                <div className="log-out" onClick={logout}>登出</div>
            </div>
            <div className="title">现拥房源</div>
            <div className='info'>
                {houses && houses.length > 0 &&
                    houses.map((house: House, i: number) => (
                        <div className='card' onClick={() => { showHouseDetail(house) }}>
                            <div className="pic1">
                                {house.pics && house.pics.length > 0 && <img className='pic-img' id={'pic-img' + i} src={house.pics[0].url} alt="" />}
                            </div>
                            <div className='type'>房源类型: {house.type}</div>
                            <div className='address'>房源地址: {house.location}</div>
                            {/* <div>{house.description}</div>
                            <div>{house.available ? '可用' : '不可用'}</div> */}

                        </div>
                    ))}
                <div className="card more" onClick={() => setshowHouseDialog(true)}>
                    <div>
                        <p className='add-more'>+</p>
                    </div>
                </div>
                <div className="blank"></div>
            </div>
            <UpHouseDialog
                show={showHouseDialog}
                hide={() => setshowHouseDialog(false)}
                cos={cos}
                user={user}
            />
            <MeetDialog
                show={showMeetDialog}
                hide={() => { setshowMeetDialog(false) }}
                user={user}
                meets={meets}
            />
            <HouseDetailDialog
                show={showHouseDetailDialog}
                hide={() => { setshowHouseDetailDialog(false) }}
                user={user}
                house={d_house}
            />
        </div >
    )
}

export default SendHouse